package com.ygxsk.carhome.imagepick;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.ConvertUtils;
import com.blankj.utilcode.util.ScreenUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.blankj.utilcode.util.Utils;
import com.ygxsk.carhome.R;
import com.ygxsk.carhome.alertview.AlertView;
import com.ygxsk.carhome.alertview.OnItemClickListener;
import com.ygxsk.carhome.constant.ConstantSign;

import java.util.List;

/**
 * Author 姚智胜
 * Version V1.0版本
 * Description:
 * Date: 2017/4/10
 */
public class ImageShowPickerAdapter extends RecyclerView.Adapter<ImageShowPickerAdapter.ViewHolder>
        implements ImageShowPickerPicListener {

    /**
     * 控件外侧传递的要求添加的最多几张图片内容
     */
    private final int mMaxNum;

    private final Context context;

    private final List<ImageShowPickerBean> listImages;

    public ImageLoaderInterface imageLoaderInterface;

    private final ImageShowPickerListener pickerListener;

    /**
     * 监听设置长按是否可以被长按的标识.默认是true 2020-6-16 11:31:34
     */
    private boolean isCanOnLongClick = true;

    private static int iconHeight;

    private int delPicRes;

    private static final float DEFUALT_SPACING_LEFT = 15f;
    private static final float DEFUALT_SPACING_RIGHT = 15f;

    //添加图片的资源内容
    private int addPicRes;

    private boolean isShowAnim;

    private boolean isShowDel;

    public void setShowDel(boolean showDel) {
        isShowDel = showDel;
    }

    /**
     * 设置是否可以直接长按点击删除图片
     */
    public void setIsCanOnLongClick(boolean _isCanOnLongClick) {
        isCanOnLongClick = _isCanOnLongClick;
    }

    public void setShowAnim(boolean showAnim) {
        isShowAnim = showAnim;
    }

    public void setIconHeight(int iconHeight) {
        ImageShowPickerAdapter.iconHeight = iconHeight;
    }

    public void setDelPicRes(int delPicRes) {
        this.delPicRes = delPicRes;
    }

    public void setAddPicRes(int addPicRes) {
        this.addPicRes = addPicRes;
    }

    public ImageShowPickerAdapter(int mMaxNum,//
                                  Context context,//
                                  List<ImageShowPickerBean> list, //
                                  ImageLoaderInterface imageLoaderInterface, //
                                  ImageShowPickerListener pickerListener,//
                                  boolean _isCanOnLongClick) {//是否可以
        this.mMaxNum = mMaxNum;
        this.context = context;
        this.listImages = list;
        this.imageLoaderInterface = imageLoaderInterface;
        this.pickerListener = pickerListener;
        this.isCanOnLongClick = _isCanOnLongClick;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        //第一个版本的 原始代码内容start===================================================
        //LogUtils.d("itchen---填充图片九宫格之前-------->");

        //这里是填充布局内容 layoutviewholderimage
        /*FrameLayout frameLayout = new FrameLayout(context);
        parent.addView(frameLayout);

        frameLayout.setLayoutParams(new FrameLayout.LayoutParams(//
                FrameLayout.LayoutParams.WRAP_CONTENT, //
                FrameLayout.LayoutParams.WRAP_CONTENT));//

        ViewHolder vh = new ViewHolder(frameLayout, //
                imageLoaderInterface,//
                this);//

        frameLayout.addView(vh.iv_pic);*/
        //frameLayout.addView(vh.iv_del);//添加删除按钮内容。
        //原始代码内容 end ===================================================


        //使用真实布局添加代码
        //第二个版本的内容 start======================================================================================================
        //原始代码
        //View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layoutviewholderimage,parent,false);
        //2019年10月23日还需要改造，为什么不能靠左直接展示？为何会有间距？
        //itchen改造,
        /*View view = LayoutInflater.from(Utils.getApp()).inflate(R.layout.layoutviewholderimage,parent,false);

        ViewHolder viewHolder = new ViewHolder(//
                view,//
                imageLoaderInterface,//
                this);*/

        //第二个版本的内容 end======================================================================================================

        //LogUtils.d("itchen---填充图片九宫格之后-------->");

        //第三个版本内容
        View view = LayoutInflater.from(Utils.getApp()).inflate(R.layout.layoutviewholdernine, parent, false);

        ViewHolder viewHolder = new ViewHolder(//
                view,//
                imageLoaderInterface,//
                this);//

        return viewHolder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {


        /*ViewGroup.LayoutParams layoutParams = holder.imageViewInHolder.getLayoutParams();
        //ViewGroup.LayoutParams params = imageViewInHolder.getLayoutParams();
        layoutParams.width = (int) (((ScreenUtils.getScreenWidth()-(ConvertUtils.dp2px(DEFUALT_SPACINGOUT)*2))/3));

        LogUtils.d("itchen---宽度="+layoutParams.width);
        layoutParams.height =  layoutParams.width;//保持宽高一样

            if (position==2//
                    ||position==5//
                    ||position==8){//

                holder.textViewRightImage.setVisibility(View.GONE);

            }else{
                holder.textViewRightImage.setVisibility(View.VISIBLE);
            }

        holder.imageViewInHolder.setLayoutParams(layoutParams);*/
        //LogUtils.d("itchen--->position="+position);

        /*if (position==2//
                ||position==5//
                ||position==8){//

            holder.textViewRightImage.setVisibility(View.GONE);

        }else{
            holder.textViewRightImage.setVisibility(View.VISIBLE);
        }*/

        //this.notifyDataSetChanged();


        if (listImages.size() == 0 || listImages.size() == position) {//如果列表内没有添加图片，则展示添加图片入口图片id为holder.iv_pic

            imageLoaderInterface.displayImage(context, addPicRes, holder.imageViewInHolder);//添加加号按钮内容

        } else {

            if (null == listImages.get(position).getImageShowPickerUrl() || "".equals(listImages.get(position).getImageShowPickerUrl())) {
                imageLoaderInterface.displayImage(context, listImages.get(position).getImageShowPickerDelRes(), holder.imageViewInHolder);
            } else {
                imageLoaderInterface.displayImage(context, listImages.get(position).getImageShowPickerUrl(), holder.imageViewInHolder);
            }

        }

    }

    @Override
    public int getItemCount() {

        return listImages.size() < mMaxNum ? listImages.size() + 1 : listImages.size();

    }

    @Override
    public void onDelClickListener(int position) {

        listImages.remove(position);//删除的时候是做了监听删除的

        if (isShowAnim) {
            notifyItemRemoved(position);
            if (listImages.size() - 1 >= 0 && listImages.get(listImages.size() - 1) == null) {
                notifyItemChanged(listImages.size() - 1);
            } else if (listImages.size() - 1 == 0) {
                notifyItemChanged(0);
            }
        } else {
            notifyDataSetChanged();
        }

        if (pickerListener != null) {
            pickerListener.delOnClickListener(position, mMaxNum - listImages.size());
        }

    }

    @Override
    public void onPicClickListener(int position) {

        if (position == listImages.size()) {
            if (pickerListener != null) {
                pickerListener.addOnClickListener(mMaxNum - position - 1);
            }
        } else {

            if (pickerListener != null) {//
                pickerListener.picOnClickListener(//
                        listImages, //
                        position, //
                        mMaxNum > listImages.size() ? mMaxNum - listImages.size() - 1 :
                                (listImages.get(mMaxNum - 1) == null ? 1 : 0));//
            }

        }
    }

    @Override
    public void onPicLongClickListener(final int positionInImagesList) {

        if (positionInImagesList != listImages.size()) {//如果点击的不是加号按钮那么执行弹窗，是加号按钮则过滤掉

            if (isCanOnLongClick) {

                new AlertView(ConstantSign.ALERT_TITLE, //
                        "确定删除该图片吗？", //
                        "取消", //
                        new String[]{"删除"}, //
                        null, //
                        context, //
                        AlertView.Style.Alert, //
                        new OnItemClickListener() {
                            @Override
                            public void onItemClick(Object o, int position) {

                                if (position != AlertView.CANCELPOSITION) {
                                    //长按了之后 给时间也传递给叉号的事件
                                    onDelClickListener(positionInImagesList);//调用自己方法内的
                                }

                            }
                        })//
                        .setCancelable(true)//
                        .show();

            } else {
                ToastUtils.showShort(context.getString(R.string.statuscannotedit));
            }

            //正常的长按
            /*if (pickerListener != null) {
                pickerListener.longClickListener(listImages,position,//
                        mMaxNum > listImages.size() ? mMaxNum - listImages.size() - 1 :
                        (listImages.get(mMaxNum - 1) == null ? 1 : 0));//
            }*/

        } else {

            //第二种书写逻辑：执行正常的弹窗也是可以的
            if (pickerListener != null) {
                pickerListener.addOnClickListener(mMaxNum - positionInImagesList - 1);
            }

            //第一种书写逻辑：消耗长按
            //LogUtils.d("itchen---adapter内-onPicLongClickListener==" + position);
            //日志信息是：itchen---adapter内-onPicLongClickListener==0
        }
    }


    //自定义的ViewHolder，持有每个Item的的所有界面元素
    public static class ViewHolder extends RecyclerView.ViewHolder //
            implements View.OnClickListener, View.OnLongClickListener {

        //真实被填充或者替换的图片布局
        public ImageView imageViewInHolder;
        //public TextView textViewRightImage;
        //填充删除图片布局,这个在这里无用不要
        //public ImageView iv_del;

        //对图片操作的监接口类
        private final ImageShowPickerPicListener picOnClickListenerInViewHolder;


        public ViewHolder(final View view, //
                          ImageLoaderInterface imageLoaderInterface,//
                          final ImageShowPickerPicListener picOnClickListener) {//
            super(view);//

            this.picOnClickListenerInViewHolder = picOnClickListener;
            //===================================================================================================
            //原始代码不要了，改为正常的使用findviewbyid产生的。
            //iv_pic = imageLoaderInterface.createImageView(view.getContext());//创建图片视图

            imageViewInHolder = (ImageView) view.findViewById(R.id.imageviewinviewholder);
            //textViewRightImage = (TextView)view.findViewById(R.id.textviewrightimage);

            //LogUtils.d("itchen--创建ViewHolder----");

            //原始代码内容
            //2018年05月25日发现
            /*FrameLayout.LayoutParams pic_params = new FrameLayout.LayoutParams(//
                    iconHeight,//
                    iconHeight);*/

            //ViewGroup.LayoutParams pic_params = new ViewGroup.LayoutParams(iconHeight,iconHeight);
            //pic_params.setMargins(10, 10, 10, 10);
            //iv_pic.setLayoutParams(pic_params);
            //===========================================================================================
            //iv_del = new ImageView(view.getContext());//这个需求不要可以去掉。

            //FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(//
            // FrameLayout.LayoutParams.WRAP_CONTENT,//
            // FrameLayout.LayoutParams.WRAP_CONTENT);//
            //layoutParams.gravity = Gravity.TOP | Gravity.END;//
            //iv_del.setPadding(5, 5, 5, 5);
            //iv_del.setLayoutParams(layoutParams);

            //iv_pic.setId(R.id.iv_image_show_picker_pic);//所有的都是这个了
            //iv_del.setId(R.id.iv_image_show_picker_del);

            //LogUtils.d("获取位置为：" + this.getAdapterPosition());

            //2019年10月26日=================================================================================
            //重新设置图片的宽高比例
            ViewGroup.LayoutParams params = imageViewInHolder.getLayoutParams();
            //(ConvertUtils.dp2px(DEFUALT_SPACING_LEFT + 18)  后边的数字越大，那么方块的 宽高就越窄；
            params.width = (int) (((ScreenUtils.getScreenWidth() - (ConvertUtils.dp2px(DEFUALT_SPACING_LEFT + 18) + ConvertUtils.dp2px(DEFUALT_SPACING_RIGHT + 18))) / 3));
            params.height = params.width;//保持宽高一样的正方形

            imageViewInHolder.setLayoutParams(params);

            /*if (this.getAdapterPosition()==2||this.getAdapterPosition()==5||this.getAdapterPosition()==8){
                textViewRightImage.setVisibility(View.GONE);
            }else{
                textViewRightImage.setVisibility(View.VISIBLE);
            }*/

            //普通的点击事件
            imageViewInHolder.setOnClickListener(this);

            //长按点击事件--添加
            imageViewInHolder.setOnLongClickListener(this);

            //添加
            //iv_del.setOnClickListener(this);
            //LogUtils.d("itchen--创建ViewHolder----之后");

        }

        @Override
        public void onClick(View v) {

            int i = v.getId();

            if (i == R.id.imageviewinviewholder) {

                if (picOnClickListenerInViewHolder != null) {
                    picOnClickListenerInViewHolder.onPicClickListener(getLayoutPosition());
                }

            }

            /*else if (i == R.id.iv_image_show_picker_del) {//2018年05月02日长按走这里的逻辑。
                if (picOnClickListenerInViewHolder != null) {
                    picOnClickListenerInViewHolder.onDelClickListener(getLayoutPosition());
                }
            }*/

        }

        //2018年04月08日添加长按事件。
        @Override
        public boolean onLongClick(View view) {

            switch (view.getId()) {

                case R.id.imageviewinviewholder: {

                    //2018年05月02日添加消耗长按.
                    if (picOnClickListenerInViewHolder != null) {
                        picOnClickListenerInViewHolder.onPicLongClickListener(getLayoutPosition());
                    }

                    break;
                }
                default:
                    break;
            }

            return true;
        }
    }


    /*new AlertView("", //
                          "确定删除该图片吗？", //
                          "取消", //
                          new String[]{"确定"}, //
            null, //
            view.getContext(), //
    AlertView.Style.Alert, //
            new OnItemClickListener() {
        @Override
        public void onItemClick(Object o, int position) {

            if (position != AlertView.CANCELPOSITION) {
                //长按了之后 给时间也传递给叉号的事件
                if (picOnClickListener != null) {
                    picOnClickListener.onDelClickListener(getLayoutPosition());
                }
            }

        }
    })//
            .setCancelable(true)//
                            .show();*/

}


